<?php
namespace addons\caipiao\service;



use think\facade\Log;

class Qiyezf{
    private $appid;
    private $mchid;
    private $secrect_key;
    private $ip;
    private $addonInfo;
    private $cf;
    public function __construct(){
        $this->addonInfo = getAddonInfo();
        $mid= $this->addonInfo['id'];
        $this->cf=getWxpayConfig($mid);
        //企业付款到微信零钱，PHP接口调用方法
        $this->appid = $this->cf['appid'];
        $this->mchid = $this->cf['mchid'];
        $this->secrect_key = $this->cf['paysignkey'];
        $this->ip = $_SERVER['SERVER_ADDR'];
    }
    private function getCertPem(){
        $addon = $this->addonInfo['addon'];
        if(!is_dir(ROOT_PATH."data/pem")){
            mkdir(ROOT_PATH."data/pem");
        }
        $dir = ROOT_PATH."data/pem/{$addon}_apiclient_cert.pem";
        if(!file_exists($dir)){
            file_put_contents($dir,$this->cf['apiclient_cert']);
        }
        return  $dir;
    }
    private function getKeyPem(){
        $addon = $this->addonInfo['addon'];
        if(!is_dir(ROOT_PATH."data/pem")){
            mkdir(ROOT_PATH."data/pem");
        }
        $dir = ROOT_PATH."data/pem/{$addon}_apiclient_key.pem";
        if(!file_exists($dir)){
            file_put_contents($dir,$this->cf['apiclient_key']);
        }
        return  $dir;
    }
    private function createNoncestr($length =32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str ="";
        for ( $i = 0; $i < $length; $i++ )  {
            $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }

    private function unicode() {
        $str = uniqid(mt_rand(),1);
        $str=sha1($str);
        return md5($str);
    }
    private function arraytoxml($data){
        $str='<xml>';
        foreach($data as $k=>$v) {
            $str.='<'.$k.'>'.$v.'</'.$k.'>';
        }
        $str.='</xml>';
        return $str;
    }
    private function xmltoarray($xml) {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $val = json_decode(json_encode($xmlstring),true);
        return $val;
    }

    private function curl($param="",$url="",$second=30,$aHeader = array()) {
        $ch = curl_init();                                      //初始化curl
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);//设置执行最长秒数
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');//证书类型
        curl_setopt($ch, CURLOPT_SSLCERT, $this->getCertPem());//证书位置
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');//CURLOPT_SSLKEY中规定的私钥的加密类型
        curl_setopt($ch, CURLOPT_SSLKEY, $this->getKeyPem());//证书位置
        if (count($aHeader) >= 1) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);//设置头部
        }
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);//全部数据使用HTTP协议中的"POST"操作来发送
        $data = curl_exec($ch);//执行回话
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            return false;
        }
    }

    /*
    $amount 发送的金额（分）目前发送金额不能少于1元
    $re_openid, 发送人的 openid
    $desc  //  企业付款描述信息 (必填)
    $check_name    收款用户姓名 (选填)
    */
    public function sendMoney($amount,$re_openid,$partner_trade_no,$desc='测试',$check_name=''){

        $total_amount = (100) * $amount;

        $data=array(
            'mch_appid'=>$this->appid,//商户账号appid
            'mchid'=> $this->mchid,//商户号
            'nonce_str'=>$this->createNoncestr(),//随机字符串
            'partner_trade_no'=> $partner_trade_no, //date('YmdHis').rand(1000, 9999) //商户订单号
            'openid'=> $re_openid,//用户openid
            'check_name'=>'NO_CHECK',//校验用户姓名选项,
            're_user_name'=> $check_name,//收款用户姓名
            'amount'=>$total_amount,//金额
            'desc'=> $desc,//企业付款描述信息
            'spbill_create_ip'=> $this->ip,//Ip地址
        );
        $secrect_key=$this->secrect_key;///这个就是个API密码。MD5 32位。
        $data=array_filter($data);
        ksort($data);
        $str='';
        foreach($data as $k=>$v) {
            $str.=$k.'='.$v.'&';
        }
        $str.='key='.$secrect_key;
        $data['sign']=md5($str);
        $xml=$this->arraytoxml($data);

        $url='https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers'; //调用接口
        $res=$this->curl($xml,$url);
        return $this->xmltoarray($res);
        //返回来的结果
        // [return_code] => SUCCESS [return_msg] => Array ( ) [mch_appid] => wxd44b890e61f72c63 [mchid] => 1493475512 [nonce_str] => 616615516 [result_code] => SUCCESS [partner_trade_no] => 20186505080216815
        // [payment_no] => 1000018361251805057502564679 [payment_time] => 2018-05-15 15:29:50


//        $responseObj = simplexml_load_string($res, 'SimpleXMLElement', LIBXML_NOCDATA);
//        echo $res= $responseObj->return_code;  //SUCCESS  如果返回来SUCCESS,则发生成功，处理自己的逻辑
    }
}
